package com.mulanweb.api.module.controller.wechat;

import com.jfinal.kit.StrKit;
import com.mulanweb.api.module.controller.BaseController;
import com.mulanweb.api.module.model.*;
import com.mulanweb.db.common.Constant;
import com.mulanweb.handler.CouponHandler;
import com.mulanweb.handler.wechat.UserHandler;
import com.mulanweb.utils.DateUtil;
import com.mulanweb.utils.RandomUtil;
import com.mulanweb.validator.annotation.ValidateFile;
import com.mulanweb.validator.annotation.ValidateForm;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2016/11/8 0008.
 */
@ValidateFile
public class VisaOrderController extends BaseController {

    @ValidateForm
    public synchronized void save() {

        String openId = super.getSessionAttr("openId");
        //  String openId = "oULNBwOvt_D2A_8se1bQOQ06ky0w";
        Map<String, Object> result = new HashMap<String, Object>();

        if (super.getSessionAttr("tokenTime") != null) {
            Date tokenTime = super.getSessionAttr("tokenTime");
            Long tokenTimeMsec = tokenTime.getTime();
            Long currentTimeMsec = new Date().getTime();
            if ((currentTimeMsec - tokenTimeMsec) < 500) {
                returnJson(0, "操作过于频繁");
                super.setSessionAttr("tokenTime", new Date());
                return;
            } else {
                super.setSessionAttr("tokenTime", new Date());
            }
        } else {
            super.setSessionAttr("tokenTime", new Date());
        }

        User user = User.dao.findFirst("SELECT * FROM user where open_id = ?", openId);

        Long userId = null;
        if (UserHandler.userNotNull(openId)) {
            userId = user.getId();
        } else {
            returnJson(0, Constant.PromptMessage.NOT_EXIST_USER);
            return;
        }

        List<Order> userList = Order.dao.find("SELECT * FROM `order` WHERE user_id =? AND status_id = 5", userId);
        if (userList.size() > 3) {
            returnJson(0, "存在未完成支付订单");
            return;
        }

        String email = getPara("email");
        String remarks = getPara("remarks");
        String name = getPara("name");
        String phoneNumber = getPara("phoneNumber");
        Integer amount = getParaToInt("amount");
        Long couponCode = getParaToLong("couponCode");
        Integer visaChildId = getParaToInt("visaChildId");

        boolean visaCheck = true;//标记，判断签证商品是否合法
        VisaChild visaChild = VisaChild.dao.findById(visaChildId);
        Visa visa = null;
        if (visaChild != null && visaChild.getDeleteTime() == null) {
            visa = Visa.dao.findById(visaChild.getParentId());
            if (visa != null && visa.getDeleteTime() == null) {
                visaCheck = false;
            }
        }
        if (visaCheck) {
            returnJson(0, "商品已失效");
            return;
        }

        VisaOrder visaOrder = new VisaOrder();
        visaOrder.setActuallyPayment(0F);//实付款
        visaOrder.setUserId(user.getId());
        visaOrder.setShouldPayment(visaChild.getPrice());//应付款
        visaOrder.setAmount(amount);
        visaOrder.setVisaChildId(visaChildId);
        visaOrder.setEmail(email);
        visaOrder.setName(name);
        visaOrder.setPhoneNumber(phoneNumber);
        visaOrder.setRemark(remarks);
        visaOrder.setStatusId(5L);//订单未支付
        visaOrder.setCreateTime(new Date());
        String orderNumber = RandomUtil.createRandomOrderNumber();
        VisaOrder verifyOrder = VisaOrder.dao.findFirst("SELECT * FROM `visa_order` WHERE order_number = ? ", orderNumber);
        while (verifyOrder != null) {
            orderNumber = RandomUtil.createRandomOrderNumber();
            verifyOrder = VisaOrder.dao.findFirst("SELECT * FROM `visa_order` WHERE order_number = ? ", orderNumber);
        }
        visaOrder.setOrderNumber(orderNumber);
        if (visaOrder.save()) {
            result.put("returnCode", 1);
            Photo photo = Photo.dao.findFirst("SELECT * FROM photo WHERE type_id =? AND target_id=?", 18, visaChild.getId());
            result.put("orderNumber", orderNumber);
            result.put("targetLogo", photo != null ? photo.getPath() : Constant.XinXiLan.DEFAULT_PHOTO_PATH);
            Map<String, Object> target = new HashMap<String, Object>();
            target.put("price", visaChild.getPrice());
            target.put("title", visa.getTitle());
            result.put("target", target);
            //15分钟后检查订单是否支付，如未支付则将订单状态更改为已过期
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                public void run() {
                    VisaOrder checkOrderPayStatus = VisaOrder.dao.findById(visaOrder.getId());
                    if (checkOrderPayStatus.getPayTime() == null) {
                        checkOrderPayStatus.setStatusId(6L);//6 表示订单已过期
                        checkOrderPayStatus.update();
                        //订单已过期，返回优惠券库存
                    }
                }
            }, TimeUnit.MINUTES.toMillis(15));// 设定指定的时间time,此处为15分钟
            renderJson(result);
        } else {
            returnFailureJson();
        }
    }

}
